package org.jeecg.modules.friends.service.impl;

import java.util.Objects;

import org.jeecg.common.exception.MakeFriendsBaseException;
import org.jeecg.modules.friends.dao.TicketRecordDAO;
import org.jeecg.modules.friends.dao.VipUserDAO;
import org.jeecg.modules.friends.model.TicketRecordDO;
import org.jeecg.modules.friends.model.VipUserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TicketRecordServiceImpl implements org.jeecg.modules.friends.service.TicketRecordService {
    @Autowired
    private TicketRecordDAO ticketRecordDAO;
    @Autowired
    private VipUserDAO vipUserDAO;

    @Override
    @Transactional
    public void addTicketRecord(Long userId, Long applyId) {
        VipUserDO vipUserDO = vipUserDAO.findByUserId(userId);
        if (Objects.isNull(vipUserDO) && vipUserDO.getTicketLeft() <= 0) {
            throw new MakeFriendsBaseException("无可用券");
        }

        TicketRecordDO recordDO = new TicketRecordDO();
        recordDO.setCreateTime(System.currentTimeMillis());
        recordDO.setUpdateTime(System.currentTimeMillis());
        recordDO.setUserId(userId);
        recordDO.setVipId(vipUserDO.getId());
        recordDO.setValidStatus(0);
        recordDO.setFriendApplyId(applyId);
        ticketRecordDAO.insert(recordDO);
        vipUserDAO.minusTicket(vipUserDO.getId());
    }

    @Override
    @Transactional
    public void cancelTicketRecord(Long friendInfoId) {
        TicketRecordDO recordDO = ticketRecordDAO.findById(friendInfoId);
        if (Objects.isNull(recordDO) || recordDO.getValidStatus() != 0) {
            return;
        }
        VipUserDO vipUserDO = vipUserDAO.findByUserId(recordDO.getUserId());
        vipUserDAO.addTicket(vipUserDO.getId(), 1);
        ticketRecordDAO.updateValidStatus(recordDO.getId(), 1);
    }
}